package com.cheng.reggie.controller;

import com.cheng.reggie.common.R;
import com.cheng.reggie.config.RedisConfig;
import com.cheng.reggie.entity.User;
import com.cheng.reggie.service.UserService;
import com.cheng.reggie.util.SMSUtils;
import com.cheng.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired(required = false)
    private UserService userService;

    @Autowired(required = false)
    private RedisTemplate redisTemplate;


    //退出登录
    @RequestMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.invalidate();
        return R.success("退出登录成功");

    }

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //接收手机号码封装User对象
        //生成4位手机验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("验证码是:" + code);
        //发送手机验证码
        // SMSUtils.sendMessage("黑马旅游网","SMS_198917972", user.getPhone(), code);
        //  session.setAttribute(user.getPhone(),code);
        //把验证码存储到缓存中,并设置过期时间5分钟
        redisTemplate.opsForValue().set(user.getPhone(),code,300, TimeUnit.SECONDS);
        //返回数据,输出成功
        return R.success("发送验证码短信成功");

    }

    //处理用户登录数据
    @RequestMapping("/login")
    public R<User> longin(@RequestBody Map<String, String> map, HttpSession session){
        //1.接收数据封装到Map<String, String> map
        String phone = map.get("phone"); //输入手机号
        String userCode = map.get("code");//用户输入的验证码
        //  String  sessionCode = (String) session.getAttribute(phone);
        //从缓存里面获取验证码
        String sessionCode = (String) redisTemplate.opsForValue().get(phone);
        //3.调用业务层进行登录操作,返回登录用户对象
        User longinUser = userService.longin(phone, userCode, sessionCode);
        if (longinUser != null) {
            //登录用户有效
            session.setAttribute("user",longinUser.getId());
            //登录成功后,session验证码设置失效
            //session.removeAttribute(phone);
            //将缓存中的验证码删除
            redisTemplate.delete(phone);
            //返回成功数据
            return R.success(longinUser);
        }
        return  R.error("登录失败");
    }

}
